// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "DBManager/Database/IDatabase.h"

#include <cstddef>
#include <string>
#include <typeinfo>
#include <utility>

#include "DataStructure/Common/Status.h"

using namespace SG::DBManager;

// ====================================================================================================================
std::vector<IDatabaseHub::FunCopyDataRes> IDatabaseHub::s_copyDataResFunVec = {};
IDatabaseHub::IDatabaseHub (/* args */) = default;

IDatabaseHub::~IDatabaseHub ()
{
    IDatabaseHub::ClearSignal ();
}

void IDatabaseHub::ClearSignal ()
{
    m_getAllCoordFunMap.clear ();
    m_getElementNodesByIdFunMap.clear ();
}

// ====================================================================================================================
/**
 * @brief 构造函数，使用给定的路径和文件名初始化数据库。
 * @param foldPath 数据库文件的路径。
 * @param fileName 数据库文件的名称。
 */
IDatabase::IDatabase (std::uint8_t databaseType, std::string foldPath, std::string fileName)
    : m_databaseType (databaseType), m_fileName (std::move (fileName)), m_foldPath (std::move (foldPath))
{
    m_fullpath    = m_foldPath + "/" + m_fileName;
    m_dataOperate = new DataOperate (this);
}

/**
 * @brief 析构函数。
 */
IDatabase::~IDatabase ()
{
    if (m_dataOperate != nullptr)
    {
        delete m_dataOperate;
        m_dataOperate = nullptr;
    }

    m_partitionElementMap.clear ();
};

#include <iostream>
/**
 * @brief 更新数据存储库，如果存储库不存在则创建它。
 * @param typeInfo 存储库类型的信息。
 * @return 如果更新成功则返回 true，否则返回 false。
 */
SG::DataStructure::Common::Status IDatabase::UpdataRepository (const std::type_info& typeInfo)
{
    auto typeID = typeInfo.hash_code ();
    auto iter   = m_dataRepositories.find (typeID);
    if (iter == m_dataRepositories.end ())
    {
        return CreateRepository (typeInfo);
    }
    return SG::DataStructure::Common::Status::STATUS_Success;
}

/**
 * @brief 获取仓库指针
 * @return 仓库指针
 */
void* IDatabase::GetDataRepositorieP (std::size_t RepKey) const
{
    auto iter = m_dataRepositories.find (RepKey);
    if (iter != m_dataRepositories.end ())
    {
        return iter->second.get ();
    }
    return nullptr;
}
